package cn.wolfcode.trip.app.filter;

import cn.wolfcode.trip.base.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class ImageFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //获取请求的图片地址
        String uri = req.getRequestURI();
        //获取图片完整路径
        File file = new File(UploadUtil.PATH, uri);
        if (file.exists()) {
            //把图片的文件内容转成byte数组
            byte[] bytes = FileUtils.readFileToByteArray(file);
            //把byte数组输出给浏览器
            response.getOutputStream().write(bytes);
        }else{

            chain.doFilter(req, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void destroy() {

    }
}
